package com.example.a13001.shoppingmalltemplate.fragments;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.activitys.AffirmOrderActivity;
import com.example.a13001.shoppingmalltemplate.activitys.IntegralOrderListActivity;
import com.example.a13001.shoppingmalltemplate.activitys.LoginActivity;
import com.example.a13001.shoppingmalltemplate.adapters.ShopCarLvAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.event.AddShopCarEvent;
import com.example.a13001.shoppingmalltemplate.modle.AppConfig;
import com.example.a13001.shoppingmalltemplate.modle.CloaseAccount;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.Goods;
import com.example.a13001.shoppingmalltemplate.modle.LoginStatus;
import com.example.a13001.shoppingmalltemplate.modle.ShopCarGoods;
import com.example.a13001.shoppingmalltemplate.mvpview.ShopCarView;
import com.example.a13001.shoppingmalltemplate.presenter.ShopCarPredenter;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ShopCarFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ShopCarFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopCarFragment extends Fragment implements View.OnClickListener, ShopCarLvAdapter.CheckInterface, ShopCarLvAdapter.ModifyCountInterface, ShopCarLvAdapter.doDeleteMessageInterface {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ListView mLvShopCar;
    private List<ShopCarGoods.ListBean> mList;
    private ShopCarLvAdapter mAdapter;
    private TextView mTvEdit;
    private boolean flag = false;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private TextView mTvTotal;//合计
    private CheckBox mCbAll;//全选
    private TextView mTvCloseAccount;//结算
//    private CheckBox mCbTop;
    private LinearLayout mLlTotal;
    private TextView mTvTitleCenter;//标题
    ShopCarPredenter shopCarPredenter=new ShopCarPredenter(getActivity());
    private static final String TAG = "ShopCarFragment";
    private int ifLogin=-1;
    private SmartRefreshLayout mSrflShopCar;
    private String code;//安全码

    public ShopCarFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShopCarFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShopCarFragment newInstance(String param1, String param2) {
        ShopCarFragment fragment = new ShopCarFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        Log.e(TAG, "onCreate: "+mParam1+mParam2 );
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_shop_car, container, false);
        initView(view);
        initData();
        initListener();
        getData();
        return view;
    }
    /**
     * 初始化控件
     * @param view
     */
    private void initView(View view) {
        view.findViewById(R.id.iv_title_back).setVisibility(View.GONE);
        mTvTitleCenter = (TextView) view.findViewById(R.id.tv_title_center);
        mTvTitleCenter.setText("购物车");
        mLvShopCar = view.findViewById(R.id.lv_shopcar);
        mTvEdit = view.findViewById(R.id.tv_shopcar_edit);
        mTvTotal = view.findViewById(R.id.tv_shopcar_total);
        mCbAll = view.findViewById(R.id.cb_shopcar_all);
//        mCbTop = view.findViewById(R.id.cb_shopcar_top);
        mTvCloseAccount = view.findViewById(R.id.tv_shopcar_closeaccount);
        mLlTotal = view.findViewById(R.id.ll_shopcar_total);
//        mSrflShopCar = view.findViewById(R.id.srfl_shopcar);
        mLvShopCar.setEmptyView(view.findViewById(R.id.list_empty));
    }
    /**
     * 初始化数据源
     */
    private void initData() {
        String safetyCode = MyUtils.getMetaValue(getActivity(), "safetyCode");
        code = Utils.md5(safetyCode+Utils.getTimeStamp());

        shopCarPredenter.onCreate();
        shopCarPredenter.attachView(shopCarView);

        mList = new ArrayList<>();
        mAdapter=new ShopCarLvAdapter(getActivity(),mList);

        mAdapter.setCheckInterface(this);
        mAdapter.setModifyCountInterface(this);
        mLvShopCar.setAdapter(mAdapter);

        mAdapter.setDoDeleteMessageInterface(this);
    }
    /**
     * 获取网络数据
     */
    private void getData() {
        //购物车商品列表
        shopCarPredenter.getShopCarGoods(AppConstants.COMPANY_ID,AppConstants.FROM_MOBILE);
        //登录状态
        shopCarPredenter.getLoginStatus(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(),AppConstants.FROM_MOBILE);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e(TAG, "onHiddenChanged: "+hidden );
//        mCbAll.performClick();
//        for (int i = 0; i < mList.size(); i++) {
//            mList.get(i).setChoosed(true);
//        }
//        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("ShopCarFragment", "setUserVisibleHint: "+isVisibleToUser );
    }

    //    private void setRefresh() {
//        //刷新
//        mSrflShopCar.setRefreshHeader(new ClassicsHeader(getActivity()));
//        mSrflShopCar.setRefreshFooter(new ClassicsFooter(getActivity()));
////        mRefresh.setEnablePureScrollMode(true);
//        mSrflShopCar.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                pageindex = 1;
//                if (mList != null) {
//                    mList.clear();
//                }
//                integralOrderListPredenter.getOrderList(AppConstants.COMPANY_ID,code,timestamp,AppConstants.PAGE_SIZE,pageindex,status,"","","",AppConstants.FROM_MOBILE);
//                refreshlayout.finishRefresh(2000/*,true*/);//传入false表示刷新失败
//            }
//        });
//        mSrflShopCar.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(RefreshLayout refreshlayout) {
//                pageindex++;
//                integralOrderListPredenter.getOrderList(AppConstants.COMPANY_ID,code,timestamp,AppConstants.PAGE_SIZE,pageindex,status,"","","",AppConstants.FROM_MOBILE);
//                refreshlayout.finishLoadMore(2000/*,true*/);//传入false表示加载失败
//            }
//        });
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addShopCarSuccess(AddShopCarEvent obj) {
        String msg = "onEventMainThread收到了消息：" + obj.getMsg();
        Log.e("ddd", "addShopCarSuccess: "+msg);
        if (!TextUtils.isEmpty(msg)){
            if ("成功".equals(obj.getMsg())||"提交订单成功".equals(obj.getMsg())){
                if (mList != null) {
                    mList.clear();
                }
                shopCarPredenter.getShopCarGoods(AppConstants.COMPANY_ID,AppConstants.FROM_MOBILE);
//                mCbTop.setChecked(false);
                try {
//                    mCbAll.setChecked(true);
                    for (int i = 0; i < mList.size(); i++) {
                        mList.get(i).setChoosed(true);
                    }
                    mAdapter.notifyDataSetChanged();
                }catch (Exception e){

                }

//                mCbAll.performClick();
//                mTvTotal.setText("合计:0.00");
            }
        }


    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: "+"dfg" );
    }

    ShopCarView shopCarView=new ShopCarView() {
        //获取购物车商品信息
        @Override
        public void onSuccess(ShopCarGoods shopCarGoods) {
            Log.e(TAG, "onSuccess: "+shopCarGoods.toString());
            int status=shopCarGoods.getStatus();
            if (status>0){
//                mCbAll.performClick();

                mList.addAll(shopCarGoods.getList());
                for (int i = 0; i < mList.size(); i++) {
                    mList.get(i).setChoosed(true);
                }
                mCbAll.setChecked(true);
//                mAdapter.notifyDataSetChanged();
                mAdapter.notifyDataSetChanged();

            }else{
                mAdapter.notifyDataSetChanged();
//                Toast.makeText(getActivity(), ""+shopCarGoods.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onSuccessGetAppConfig(AppConfig appConfig) {

        }

        //判断登录状态
        @Override
        public void onSuccessLoginStatus(LoginStatus loginStatus) {
            Log.e(TAG, "onSuccessLoginStatus: "+loginStatus.toString());
            int status=loginStatus.getStatus();
            if (status>0){
                ifLogin=1;
            }else{
                ifLogin=0;
            }
        }
        //删除购物车商品
        @Override
        public void onSuccessDeleteShopCar(CommonResult commonResult) {
            Log.e(TAG, "onSuccessDeleteShopCar: "+commonResult.toString() );
            int status=commonResult.getStatus();
            if (status>0){
                Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                if (mList != null) {
                    mList.clear();
                }
                shopCarPredenter.getShopCarGoods(AppConstants.COMPANY_ID,AppConstants.FROM_MOBILE);
            }else{
                Toast.makeText(getActivity(), ""+commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }
        //结算
        @Override
        public void onSuccessDoCloaseAccount(CloaseAccount cloaseAccount) {
            Log.e(TAG, "onSuccessDoCloaseAccount: "+cloaseAccount.toString() );
        }
        //更新购物车数量
        @Override
        public void onSuccessUpdateShopCarNum(CommonResult commonResult) {
            Log.e(TAG, "onSuccessUpdateShopCarNum: "+commonResult.toString() );
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: "+result);
        }
    };
    /**
     * 初始化数据监听
     */
    private void initListener() {
        mTvEdit.setOnClickListener(this);
        mCbAll.setOnClickListener(this);
//        mCbTop.setOnClickListener(this);
        mTvCloseAccount.setOnClickListener(this);
    }





    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * 各控件的点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //编辑
            case R.id.tv_shopcar_edit:
                flag = !flag;
                if (flag) {
                    mTvEdit.setText("完成");
                    mAdapter.isShow(true);
                    mTvCloseAccount.setText("删除");
                    mLlTotal.setVisibility(View.INVISIBLE);

                } else {
                    mTvEdit.setText("编辑");
                    mAdapter.isShow(false);
                    mTvCloseAccount.setText("结算");
                    mLlTotal.setVisibility(View.VISIBLE);
                    }
                break;
                //全选
            case R.id.cb_shopcar_all:
                Log.e(TAG, "onClick: "+"aaall" );
                if (mList!=null&&mList.size()!=0){
                    if (mCbAll.isChecked()){
//                        mCbTop.setChecked(true);
                        for (int i = 0; i < mList.size(); i++) {
                            mList.get(i).setChoosed(true);
                        }
                        mAdapter.notifyDataSetChanged();
                    }else{
//                        mCbTop.setChecked(false);
                        for (int i = 0; i < mList.size(); i++) {
                            mList.get(i).setChoosed(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            //全选
//            case R.id.cb_shopcar_top:
//                if (mList!=null&&mList.size()!=0){
//                    if (mCbTop.isChecked()){
//                        mCbAll.setChecked(true);
//                        for (int i = 0; i < mList.size(); i++) {
//                            mList.get(i).setChoosed(true);
//                        }
//                        mAdapter.notifyDataSetChanged();
//                    }else{
//                        mCbAll.setChecked(false);
//                        for (int i = 0; i < mList.size(); i++) {
//                            mList.get(i).setChoosed(false);
//                        }
//                        mAdapter.notifyDataSetChanged();
//                    }
//                }
//                statistics();
//                break;
                //结算删除
            case R.id.tv_shopcar_closeaccount:
                if (ifLogin!=-1){

                if (ifLogin>0){

                    if ("结算".equals(mTvCloseAccount.getText().toString().trim())){
                        doJieSuan();
//
                    }else if ("删除".equals(mTvCloseAccount.getText().toString().trim())){
                        doDelete();
                    }
                }else{
                    startActivityForResult(new Intent(getActivity(),LoginActivity.class).putExtra("type", "allorder"),1);
//                    Toast.makeText(getActivity(), "您还没有登录，请先登录", Toast.LENGTH_SHORT).show();
                }

                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                String login=data.getStringExtra("login");
                if ("登录成功".equals(login)){
                if ("结算".equals(mTvCloseAccount.getText().toString().trim())){
                    doJieSuan();
//
                }else if ("删除".equals(mTvCloseAccount.getText().toString().trim())){
                    doDelete();
                }}
                break;
        }
    }

    /**
     * 单选
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGrour(int position, boolean isChecked) {
        mList.get(position).setChoosed(isChecked);
        if (isAllCheck()){
            mCbAll.setChecked(true);
//            mCbTop.setChecked(true);
        }else{
            mCbAll.setChecked(false);
//            mCbTop.setChecked(false);
        }
        mAdapter.notifyDataSetChanged();
        statistics();

    }
    /**
     * 遍历list集合,判斷是否全選
     * @return
     */
    private boolean isAllCheck() {

        for (ShopCarGoods.ListBean group : mList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }
    /**
     * 增加
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        int currentCount= mList.get(position).getCommodityNumber();
        currentCount++;
        mList.get(position).setCommodityNumber(currentCount);
        ((TextView)showCountView).setText(currentCount+"");
        shopCarPredenter.updateShopCarNum(AppConstants.COMPANY_ID,mList.get(position).getCartId(),currentCount);
        mAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 删减
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        int currentCount= mList.get(position).getCommodityNumber();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        mList.get(position).setCommodityNumber(currentCount);
        ((TextView)showCountView).setText(currentCount+"");
        shopCarPredenter.updateShopCarNum(AppConstants.COMPANY_ID,mList.get(position).getCartId(),currentCount);
        mAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < mList.size(); i++) {
            ShopCarGoods.ListBean shoppingCartBean = mList.get(i);
            if (shoppingCartBean.isChoosed()) {
                totalCount++;
                Log.e("aaa","------->"+shoppingCartBean.getCommodityXPrice() * shoppingCartBean.getCommodityNumber());
                totalPrice += shoppingCartBean.getCommodityXPrice() * shoppingCartBean.getCommodityNumber() ;
            }
        }
        DecimalFormat df=new DecimalFormat("0.00");
       String ss= df.format(totalPrice);
       if (".00".equals(ss)){
           mTvTotal.setText("合计:0.00"  );
       }else{
           mTvTotal.setText("合计:" +ss );
       }

//        tvSettlement.setText("结算(" + totalCount + ")");
        Log.e("aaa","------->"+totalPrice);
    }
    @Override
    public void childDelete(int position) {

    }
    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    protected void doJieSuan() {

        List<ShopCarGoods.ListBean> toBeDeleteGroups = new ArrayList<>();// 待删除的组元素列表
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < mList.size(); i++) {
            ShopCarGoods.ListBean group = mList.get(i);
            if (group.isChoosed()) {
                toBeDeleteGroups.add(group);
                sb.append(String.valueOf(group.getCartId())+",");

            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1); //调用 字符串的deleteCharAt() 方法,删除最后一个多余的逗号
            startActivity(new Intent(getActivity(), AffirmOrderActivity.class).putExtra("cartId",sb.toString()));
        }else {
            Toast.makeText(getActivity(), "您还没有选择宝贝哦~", Toast.LENGTH_SHORT).show();
        }

//        Log.e(TAG, "doJieSuan: "+sb.toString()+AppConstants.COMPANY_ID+code+Utils.getTimeStamp()+sb.toString()+AppConstants.FROM_MOBILE);
//        shopCarPredenter.doCloaseAccount(AppConstants.COMPANY_ID,code,Utils.getTimeStamp(),sb.toString(),AppConstants.FROM_MOBILE);
//        mList.removeAll(toBeDeleteGroups);
//        mAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    protected void doDelete() {

        List<ShopCarGoods.ListBean> toBeDeleteGroups = new ArrayList<>();// 待删除的组元素列表
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < mList.size(); i++) {
            ShopCarGoods.ListBean group = mList.get(i);
            if (group.isChoosed()) {
                toBeDeleteGroups.add(group);
                sb.append(String.valueOf(group.getCartId())+",");

            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1); //调用 字符串的deleteCharAt() 方法,删除最后一个多余的逗号
        }
        Log.e(TAG, "doDelete: "+sb.toString());
        shopCarPredenter.deleteShopCar(AppConstants.COMPANY_ID,sb.toString());
//        mList.removeAll(toBeDeleteGroups);
//        mAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 单个商品删除
     * @param cartid
     */
    @Override
    public void doDelete(int cartid) {
        shopCarPredenter.deleteShopCar(AppConstants.COMPANY_ID, String.valueOf(cartid));
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
